#region Using

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text;
using System.Globalization;
using BlogEngine.Core;
using BlogEngine.Core.Provider;
using BlogEngine.Core.Provider.Interfaces;

#endregion

namespace BlogEngine.Core.Provider.MSSQL
{
  /// <summary>
  /// Microsoft SQL Server Implementation of BlogProvider
  /// </summary>
	public class CIPingServices : IPingServices
  {
     /// <summary>
     /// Loads the ping services.
     /// </summary>
     /// <returns></returns>
     public  StringCollection Load()
     {
         StringCollection col = new StringCollection();
         SQLManagedConnection myConn = SQLManagedConnection.GetConnection(Provider.DatabaseName);

         try
         {
             //get a command and reader - the non transactional reader will auto close the connection when closed
             myConn.GetTextCommand("SELECT Link FROM be_PingService");
             using (IDataReader rdr = myConn.ExecuteReader())
             {
                 while (rdr.Read())
                 {
                     if (!col.Contains(rdr.GetString(0)))
                         col.Add(rdr.GetString(0));
                 }

                 rdr.Close();
             }
         }
         finally
         {
             myConn.CloseIfNonTransactional();
         }

        return col;
     }

     /// <summary>
     /// Saves the ping services.
     /// </summary>
     /// <param name="services">The services.</param>
     public  void Save(StringCollection services)
     {
         if (services == null)
             throw new ArgumentNullException("services");

         //get a transaction based connection - that way we can rollback if anything goes wrong.
         SQLManagedConnection myConn = SQLManagedConnection.GetConnectionForTransaction(Provider.DatabaseName);

         try
         {
             //bin the old data
             myConn.GetTextCommand("DELETE FROM be_PingService");
             myConn.ExecuteNonQuery();

             foreach (string service in services)
             {
                 myConn.GetTextCommand("INSERT INTO be_PingService (Link) VALUES (@link)");
                 myConn.AddInParameter("@link", DbType.String, service);

                 myConn.ExecuteNonQuery();
             }

             myConn.Commit();
         }
         finally
         {
             //try to rollback just incase - if commit worked this will do nothing
             myConn.Rollback();
         }
     }

  }
}
